/**
 * Aistarfish.com Inc.
 * Copyright (c) 2017-2019 All Rights Reserved.
 */
package com.xf.service;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import com.qingstor.sdk.config.EvnContext;
import com.qingstor.sdk.exception.QSException;
import com.qingstor.sdk.service.Bucket;
import com.qingstor.sdk.service.QingStor;

/**
 *
 * @author xiangfeng
 * Created by on 2019-12-18 16:27
 */
public class FileService {

    private Logger LOGGER = LoggerFactory.getLogger(FileService.class);
    private final static String URL_PREFIX = "https://";

    private String endpoint;
    private String accessId;
    private String accessKey;
    private String zone;
    private String bucketName;
    private Bucket bucket;

    public void init(String accessId, String accessKey, String endpoint, String zone,
                     String bucketName) {
        this.endpoint = endpoint;
        this.accessId = accessId;
        this.accessKey = accessKey;
        this.zone = zone;
        this.bucketName = bucketName;
        EvnContext evn = new EvnContext(this.accessId, this.accessKey);
        QingStor storService = new QingStor(evn, zone);
        bucket = storService.getBucket(bucketName, zone);
    }

    public String putObject(String fileContentType, InputStream in, String fileName,
                            long fileLength) throws QSException {
        if (StringUtils.isEmpty(fileContentType) || StringUtils.isEmpty(fileName)) {
            return null;
        }
        Bucket.PutObjectInput input = new Bucket.PutObjectInput();
        input.setBodyInputStream(in);
        input.setContentType(fileContentType);
        input.setContentLength(fileLength);
        Bucket.PutObjectOutput output = null;
        output = this.bucket.putObject(fileName, input);
        if (output.getCode() != null) {
            LOGGER.error(
                    "put object failed, code=" + output.getCode() + ",msg=" + output.getMessage()
                    + ",requestId=" + output.getRequestId());
            return null;
        }
        return fileName;
    }

    public String putObject(String fileContentType, File file, String fileName,
                            long fileLength) throws QSException {
        if (StringUtils.isEmpty(fileContentType) || StringUtils.isEmpty(fileName)) {
            return null;
        }
        Bucket.PutObjectInput input = new Bucket.PutObjectInput();
        input.setBodyInputFile(file);
        input.setContentType(fileContentType);
        input.setContentLength(fileLength);
        Bucket.PutObjectOutput output = null;
        output = this.bucket.putObject(fileName, input);
        if (output.getCode() != null) {
            LOGGER.error(
                    "put object failed, code=" + output.getCode() + ",msg=" + output.getMessage()
                    + ",requestId=" + output.getRequestId());
            return null;
        }
        return fileName;
    }

    public String getAccessUrl(String path, Long expireTime) {
        if (StringUtils.isEmpty(path)) {
            LOGGER.error("path is null");
            return null;
        }
        //兼容携带域名URL
        URI uri;
        try {
            uri = new URI(path);
        } catch (URISyntaxException e) {
            LOGGER.error("getSignUrl error: ", e);
            return null;
        }
        if (!StringUtils.isEmpty(uri.getHost()) && !uri.getHost().endsWith(endpoint)) {
            //非endpoint oss,非青云的连接
            return path;
        }

        //qingstor连接,完整url
        String tempPath;
        if (StringUtils.isEmpty(uri.getHost())) {
            tempPath = path;
        } else {
            tempPath = uri.getPath();
        }
        //提取出来的uri中,temppath包含了
        if (tempPath.startsWith("/")) {
            tempPath = tempPath.replaceFirst("/", "");
        }
        return getFullUrl(tempPath, expireTime);
    }

    private String getFullUrl(String path, Long expireTime) {
        //加签
        return URL_PREFIX + bucketName + "." + zone + "." + endpoint + "/" + path;
    }

}
